package com.rfsp.mcp.controller.hos;

import java.util.Date;

import javax.validation.Valid;

import com.rfsp.mcp.pojo.vo.PfmVO;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.rfsp.common.base.ResultListVO;
import com.rfsp.common.base.ResultVO;
import com.rfsp.common.interceptor.Token;
import com.rfsp.common.interceptor.TokenType;
import com.rfsp.common.log.TrcMsg;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.BeanUtil;
import com.rfsp.common.util.XssUtils;
import com.rfsp.mcp.pojo.dto.AuthDTO;
import com.rfsp.mcp.pojo.dto.AuthStopDTO;
import com.rfsp.mcp.pojo.po.AuthPO;
import com.rfsp.mcp.pojo.po.OrgYbjPO;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.mcp.pojo.sdto.AuthSDTO;
import com.rfsp.common.pojo.sdto.PageSDTO;
import com.rfsp.mcp.pojo.vo.AuthVO;
import com.rfsp.mcp.service.AuthService;
import com.rfsp.common.service.OrgService;
import com.rfsp.common.service.UserService;

@RequiresRoles(value={"mcp_hos"}, logical= Logical.AND)
@Controller("HosAuthController")
@RequestMapping("/hos/auth")
public class HosAuthController extends HosController {

	public Logger logger = LoggerFactory.getLogger(HosAuthController.class);

	@Autowired
	AuthService authService;

	@Autowired
	UserService userService;

	@Autowired
	OrgService orgService;



    @RequestMapping("/")
    public String index1(ModelMap model, PageSDTO pageSDTO,AuthSDTO sdto) {
        return index(model,pageSDTO,sdto);
    }
    @RequestMapping("/index")
    public String index(ModelMap model, PageSDTO pageSDTO,AuthSDTO sdto) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "index"));

		//获取登录时选择的医保平台vo
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		OrgYbjPO orgYbjPO = ShiroUtils.getAttribute("org_ybj");

    	OrgPO orgPO = ShiroUtils.getCurrentOrg();
        sdto.setMiOrgId(orgPO.getId());

        if(StringUtils.isNotBlank(sdto.getCounty())) {
        	sdto.setAreaCode(sdto.getCounty());
        }else if(StringUtils.isNotBlank(sdto.getCity())) {
        	sdto.setAreaCode(sdto.getCity().substring(0, 4));
        }else if(StringUtils.isNotBlank(sdto.getProvince())) {
        	sdto.setAreaCode(sdto.getProvince().substring(0, 2));
        }

		sdto.setPfmId(pfm.getId());
		sdto.setOrgYbjId(orgYbjPO.getId());

    	PageInfo<AuthVO> pageInfo = authService.get(XssUtils.replaceXss(sdto), pageSDTO);
    	authService.combo(pageInfo.getList());
        ResultListVO<AuthVO> vo = ResultListVO.success(pageInfo, XssUtils.replaceUnXss(sdto));
        model.put("vo", vo);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "index"));
        return "hos/auth/index";
    }



    @RequestMapping("/create")
    public String createForm(ModelMap model, AuthDTO dto) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "createForm"));

    	OrgPO miOrg = ShiroUtils.getCurrentOrg();
    	OrgPO bankOrg = orgService.get(dto.getBankOrgId());

    	UserPO userPO = ShiroUtils.getCurrentUser();
    	if(StringUtils.isBlank(userPO.getCaSubjection())) {
    		dto.setBindCfca("1");
    	}

    	dto.setMiOrgName(miOrg.getOrgName());
    	dto.setBankName(bankOrg.getOrgName());
    	dto.setBankOrgCode(bankOrg.getOrgCode());

    	dto.setAuthStartTimeStr(dto.getAuthStartTime().split("-")[0]+"年"+dto.getAuthStartTime().split("-")[1]+"月"+dto.getAuthStartTime().split("-")[2]+"日");
    	dto.setAuthEndTimeStr(dto.getAuthEndTime().split("-")[0]+"年"+dto.getAuthEndTime().split("-")[1]+"月"+dto.getAuthEndTime().split("-")[2]+"日");


    	ResultVO<AuthDTO> result = ResultVO.success(dto);
        model.put("vo", result);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "createForm"));

		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		if("0".equals(pfm.getItfType().trim()))
			return "hos/auth/createForm";
		else
			return "hos/auth/createFormYBD";
    }
    
    @PostMapping("/savePdf")
    @ResponseBody
    public ResultVO postSavePdf(ModelMap model, AuthDTO dto) {
    	return savePdf(model, dto);
    }

    @GetMapping("/savePdf")
    @ResponseBody
    public ResultVO savePdf(ModelMap model, AuthDTO dto) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "savePdf"));

    	String errorInfo = null;
    	ResultVO<?> vo = null;
    	
    	
    	if("1".equals(dto.getSignType())) {
    		//检查证书绑定情况
    		String subjectDN = XssUtils.replaceUnXssAll(dto.getSubjectDN());
    		logger.info("subjectDN  ="+subjectDN);

    		UserPO userPO = userService.getUserByCaSubjectionAndUserStatusNot4(subjectDN);
    		logger.info("userPO  ="+userPO);

    		if(userPO != null) {
    			String userCode = ShiroUtils.getCurrentUser().getUserCode();

    			if(!userCode.equals(userPO.getUserCode())) {
    				vo = ResultVO.fail("当前用户与U盾用户不一致");
    				model.put("vo", vo);

    				logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "savePdf"));
    		        return vo;
    			}
    			
    			Date now = new Date();
    			if(userPO.getCaBeginTime().compareTo(now)==1 || now.compareTo(userPO.getCaEndTime())==1) {
    				vo = ResultVO.fail("当前证书不在有效期内，请确认是否插入已绑定有效的证书？");
    				model.put("vo", vo);

    				logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "savePdf"));
    		        return vo;
    			}
    		}else {
    			vo = ResultVO.fail("未检测到已绑定有效的证书，请确认是否插入已绑定有效的证书？");
    			model.put("vo", vo);

    			logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "savePdf"));
    	        return vo;
    		}
    	}

		try {
			PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
			if("0".equals(pfm.getItfType().trim())) {
				dto = authService.savePdf(dto);
			} else {
				dto = authService.saveYBDPdf(dto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			errorInfo = "操作失败，请稍后再试";
		}

    	if(StringUtils.isBlank(errorInfo)) {
    		vo = ResultVO.success(dto);
    	}else {
    		vo = ResultVO.fail(errorInfo);
    	}
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "savePdf"));
        return vo;
    }


    @RequestMapping("/signAuth")
    @ResponseBody
    public ResultVO signAuth(ModelMap model, AuthDTO dto) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "signAuth"));

    	ResultVO<?> vo = null;
		try {
			if(authService.signPDF(dto)) {
				AuthPO authPO = authService.get(dto.getId());
				BeanUtil.copyProperties(authPO, dto);
	    		vo = ResultVO.success(dto);
	    	}else {
	    		vo = ResultVO.fail("系统错误，请联系管理员");
	    	}
		} catch (Exception e) {
			e.printStackTrace();
			vo = ResultVO.fail("系统错误，请联系管理员");
		}

		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "signAuth"));
        return vo;
    }



    @Token
    @GetMapping("/stop")
    public String stopFrom(ModelMap model,AuthStopDTO dto) {

    	ResultVO<AuthStopDTO> vo = ResultVO.success(dto);
        model.put("vo", vo);
        model.put("dto", dto);

        return "hos/auth/stopForm";
    }

    @Token(TokenType.refresh)
    @PostMapping("/stop")
    public String stop(ModelMap model, @ModelAttribute("dto") @Valid AuthStopDTO dto, BindingResult result) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "stop"));

    	String returnStr = null;

    	dto = XssUtils.replaceUnXss(dto);
    	if(result.hasErrors()) {
    		return stopFrom(model,dto);
    	}


    	try {
    		returnStr = "2".equals(authService.revokeApply(dto))?"操作成功，待资金方审批":"操作成功";
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "系统异常，请拔打客服电话400-009-0001或通过在线客服问询处理。";
		}
    	logger.info("returnStr="+returnStr);

    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "stop"));
    	return alertParentReload(model, returnStr);
    }

}